import { $api } from "./api";
import FileSaver from "file-saver";
// 获取缩略图
export const getThumbImg = (galleryId) => {
  return $api(`/mes/gallery/image/thumbnail/${galleryId}`, {
    method: "GET",
  }).then((res) => {
    if (typeof res === "string") {
      return "data:image/png;base64," + res;
    } else {
      return "";
    }
  });
};
// 获取原图
export const getRawImg = (galleryId) => {
  return $api(`/mes/gallery/image/${galleryId}`, {
    method: "GET",
    responseType: "arrayBuffer",
  }).then((response) => {
    console.log("response", response);
    let base64 =
      "data:image/png;base64," +
      btoa(
        new Uint8Array(response.data).reduce(
          (data, byte) => data + String.fromCharCode(byte),
          ""
        )
      );
    return base64;
  });
};
//上传元素图
export const uploadGalleryImage = (formData) => {
  return $api(`/mes/gallery`, {
    method: "POST",
    body: formData,
  });
};

export const uploadFile = (formData) => {
  return $api(`/resource/oss/upload`, {
    method: "POST",
    body: formData,
  });
};

// 下载文件
export const download = (url, params, fileName) => {
  return $loading(url, {
    method: "POST",
    responseType: "blob",
    body: {
      ...params,
    }
  }).then((res) => {
    const blob = new Blob([res]);
    FileSaver.saveAs(blob, fileName);
  });
};

// 获取pod分类
export const getPodCategory = () => {
  return $api(`/mes/podCategory/list`, {
    method: "GET",
  }).then((res) => {
    return res.data;
  });
};

// 获取pod分类规格
export const getPodCategorySpec = (params) => {
  return $api(`/mes/podCategorySpec/list`, {
    method: "GET",
    query: params,
  });
};

// 获取pod分类
export const getPodCategoryTenantSimple = () => {
  return $api(`/mes/podCategory/tenant/list/simple`, {
    method: "GET",
  }).then((res) => {
    return res.data;
  });
};
// 获取pod分类下的规格数据
export const getSkuByPodCategory = (podCategoryId) => {
  return new Promise((resolve, reject) => {
    useApi(
      createUrl(`/mes/podCategorySpec/list`, {
        query: {
          podCategoryId,
        },
      })
    )
      .then((res) => {
        resolve(res.data.value.rows);
      })
      .catch((err) => {
        reject(err);
      });
  });
};
// 获取全部店铺列表
export const getShopSimpleList = () => {
  return $api(`/mes/shop/list/simple`, {
    method: "GET",
  }).then((res) => {
    return res.data;
  });
};

// 获取物料分类树形列表
export const getMaterialCategoryTree = () => {
  return new Promise((resolve, reject) => {
    useApi(createUrl(`/mes/material/category/tree`))
      .then((res) => {
        resolve(res.data.value.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

// 获取pod分类树形列表
export const getPodCategoryTree = () => {
  return new Promise((resolve, reject) => {
    useApi(createUrl(`/mes/podCategory/tree`))
      .then((res) => {
        resolve(res.data.value.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

// 获取素材分类列表
export const getGalleryGroupTree = () => {
  return $api(`/mes/gallery/group/tree`, {
    method: "GET"
  });
};

// 获取商品分类列表
export const getGoodsGroupTree = () => {
  return $api(`/mes/goods/group/tree`, {
    method: "GET"
  });
};

// 获取全部仓库列表
export const getWarehouseSimpleList = () => {
  return new Promise((resolve, reject) => {
    useApi(createUrl(`/mes/warehouse/list/simple`, {}))
      .then((res) => {
        resolve(res.data.value.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

/**
 * 添加日期范围
 * @param params
 * @param dateRange
 * @param propName
 */
export const addDateRange = (params, dateRange, propName) => {
  const search = params;
  if (typeof propName === "undefined") {
    return search;
  }
  search.params =
    typeof search.params === "object" &&
    search.params !== null &&
    !Array.isArray(search.params)
      ? search.params
      : {};
  dateRange = Array.isArray(dateRange) ? dateRange : [];
  search.params["beginTime"] = dateRange[0];
  search.params["endTime"] = dateRange[1];
  search.params["timeType"] = propName;
  return search;
};

/**
 * 参数处理
 * @param {*} params  参数
 */
export const tansParams = (params) => {
  let result = "";
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    const part = encodeURIComponent(propName) + "=";
    if (value !== null && value !== "" && typeof value !== "undefined") {
      if (typeof value === "object") {
        for (const key of Object.keys(value)) {
          if (
            value[key] !== null &&
            value[key] !== "" &&
            typeof value[key] !== "undefined"
          ) {
            const params = propName + "[" + key + "]";
            const subPart = encodeURIComponent(params) + "=";
            result += subPart + encodeURIComponent(value[key]) + "&";
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&";
      }
    }
  }
  return result;
};

/**
 * 
 * @param {*} item 
 * @param {*} type 
 */
export async function loadElementImg(item, type) {
  if (type === 'front' && !item.frontImage && item.frontImageId) {
    item.frontImage = await getThumbImg(
      item.frontImageId
    );
  }
  if (type === 'back' && !item.backImage && item.backImageId) {
    item.backImage = await getThumbImg(
      item.backImageId
    );
  }
  if (type === 'stock' && !item.src && item.id) {
    item.src = await getThumbImg(
      item.id
    );
  }
  if (type === 'mall' && !item.src && item.galleryId) {
    item.src = await getThumbImg(
      item.galleryId
    );
  }
}

// 日期格式化
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null;
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}';
  let date;
  if (typeof time === 'object') {
    date = time;
  } else {
    if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
      time = parseInt(time);
    } else if (typeof time === 'string') {
      time = time
        .replace(new RegExp(/-/gm), '/')
        .replace('T', ' ')
        .replace(new RegExp(/\.[\d]{3}/gm), '');
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  };
  return format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value];
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value;
    }
    return value || 0;
  });
}